import React, { useEffect, useState, useMemo, useCallback } from 'react';
import { Form, Select, Spin, Typography, Tabs, Alert, Button } from 'antd';
import { createGlobalStyle } from 'styled-components';
import { useSelector, useDispatch } from 'react-redux';
import type { RootState } from '@/store';
import { selectAudioAffectById, updateAudio } from '@/store/audiosSlice';
import { getToneEffects, getAudioSceneEffects, getSpeechToSongEffects } from '@/services/project';

const { Title, Text } = Typography;
const { Option } = Select;

// 全局 Ant Design 深色主题样式
const GlobalAntdDarkThemeStyle = createGlobalStyle`
    /* 自定义滚动条样式 */
    .config-panel-scroll::-webkit-scrollbar {
        width: 3px; background: transparent;
    }
    .config-panel-scroll::-webkit-scrollbar-thumb {
        background: #715BB8; border-radius: 4px;
    }
    /* 表单标签 */
    .ant-form-item-label > label {
        color: #FFFFFF !important;
    }
    /* 输入/选择控件 */
    .ant-input, .ant-input-number, .ant-select-selector {
        background-color: #3C3C3C !important;
        color: #FFFFFF !important;
        border-color: #555555 !important;
    }
    .ant-input:hover, .ant-input:focus,
    .ant-select:not(.ant-select-disabled):hover .ant-select-selector {
        border-color: #888888 !important;
        box-shadow: 0 0 0 2px rgba(136, 136, 136, 0.2) !important;
    }
    .ant-select-dropdown { background-color: #3C3C3C !important; }
    .ant-select-item-option { color: #FFFFFF !important; }
    .ant-select-item-option-selected { background-color: #555555 !important; }
    .ant-select-arrow { color: #FFFFFF !important; }
    /* Tab 文字颜色改为灰色 */
    .ant-tabs-tab { 
        color: #999999 !important;
    }
    .ant-tabs-tab-active {
        color: #CCCCCC !important;
    }
    .ant-tabs-tab:hover {
        color: #BBBBBB !important;
    }
    .ant-tabs-nav::before {
        background-color: #555555 !important;
    }
    .ant-tabs-ink-bar {
        background-color: #715BB8 !important;
    }
`;

const effectTypeMap = {
    tone_effects: 'Tone_effect_type',
    scene_effects: 'Audio_scene_effect_type',
    song_effects: 'Speech_to_song_type',
};

const tabItems = [
    { key: 'tone_effects', label: '音色效果' },
    { key: 'scene_effects', label: '场景音' },
    { key: 'song_effects', label: '声音成曲' },
];

interface ConfigAudioEffectFormProps {
    audioId: string;
}

const ConfigAudioEffectForm: React.FC<ConfigAudioEffectFormProps> = ({ audioId }) => {
    const [form] = Form.useForm();
    const dispatch = useDispatch();
    const audioEffects = useSelector((state: RootState) => (audioId ? selectAudioAffectById(state, audioId) : []));
    const [audioEffectsData, setAudioEffectsData] = useState<any>({});
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [activeTab, setActiveTab] = useState('tone_effects');

    const currentEffect = useMemo(() => {
        if (!activeTab) return null;
        const type = effectTypeMap[activeTab as keyof typeof effectTypeMap];
        return audioEffects.find((e) => e.effect_type === type) || null;
    }, [audioEffects, activeTab]);

    useEffect(() => {
        const fetchAudioEffects = async () => {
            try {
                setLoading(true);
                setError(null);
                const [toneRes, sceneRes, songRes] = await Promise.all([getToneEffects(), getAudioSceneEffects(), getSpeechToSongEffects()]);
                const data: any = {};
                if (toneRes.data.success) data.tone_effects = [...(toneRes.data.data.free || []), ...(toneRes.data.data.vip || [])];
                if (sceneRes.data.success) data.scene_effects = [...(sceneRes.data.data.free || []), ...(sceneRes.data.data.vip || [])];
                if (songRes.data.success) data.song_effects = [...(songRes.data.data.free || []), ...(songRes.data.data.vip || [])];
                setAudioEffectsData(data);
            } catch (err) {
                console.error('获取音频效果数据失败:', err);
                setError('获取音频效果数据失败，请稍后重试');
            } finally {
                setLoading(false);
            }
        };
        fetchAudioEffects();
    }, []);

    // 当 Redux 或 Tab 切换时，同步当前效果到表单
    useEffect(() => {
        form.setFieldsValue({ effect: currentEffect?.params });
    }, [currentEffect, form]);

    // ✅ [核心修改 1]：创建专门用于处理下拉框变化的函数
    const handleEffectChange = useCallback(
        (selectedValue: string | undefined) => {
            if (!audioId || !activeTab) return;

            const type = effectTypeMap[activeTab as keyof typeof effectTypeMap];
            // 基于当前的 Redux state 创建一个副本
            let updatedEffects = [...audioEffects];

            // 查找当前 Tab 对应的效果是否已存在
            const effectIndex = updatedEffects.findIndex((e) => e.effect_type === type);

            if (selectedValue) {
                // 如果用户选择了一个效果 (selectedValue 有值)
                const newEffect = { effect_type: type, params: selectedValue };
                if (effectIndex !== -1) {
                    // 如果已存在，则更新它
                    updatedEffects[effectIndex] = newEffect;
                } else {
                    // 如果不存在，则添加它
                    updatedEffects.push(newEffect);
                }
            } else {
                // 如果用户清除了选择 (selectedValue is undefined)
                // 并且该效果确实存在于数组中，则移除它
                if (effectIndex !== -1) {
                    updatedEffects.splice(effectIndex, 1);
                }
            }

            // 派发 action 更新 Redux
            dispatch(
                updateAudio({
                    id: audioId,
                    updates: { affect: updatedEffects },
                })
            );
        },
        [audioId, audioEffects, activeTab, dispatch]
    );

    const effectsForCurrentTab = audioEffectsData[activeTab] || [];

    const renderContent = () => {
        if (loading) {
            return (
                <div style={{ textAlign: 'center', padding: '50px 0' }}>
                    <Spin size="large" />
                    <div style={{ marginTop: 16, color: '#FFFFFF' }}>加载音频效果中...</div>
                </div>
            );
        }
        if (error) {
            return <Alert message="加载失败" description={error} type="error" showIcon />;
        }
        return (
            <>
                <Title level={5} style={{ marginTop: 0, marginBottom: 8, color: '#FFFFFF' }}>
                    当前选择
                </Title>
                <div
                    style={{
                        backgroundColor: '#3C3C3C',
                        color: '#FFFFFF',
                        padding: '8px 12px',
                        borderRadius: '4px',
                        marginBottom: '16px',
                        border: '1px solid #555555',
                    }}
                >
                    <Text style={{ color: '#FFFFFF' }}>{currentEffect ? `${tabItems.find((t) => t.key === activeTab)?.label}: ${currentEffect.params}` : '无选择效果'}</Text>
                </div>
                <Tabs activeKey={activeTab} onChange={setActiveTab} items={tabItems} />
                {/* ✅ [核心修改 2]：移除 Form 上的 onValuesChange */}
                <Form form={form} layout="vertical">
                    <Form.Item label="选择效果" name="effect">
                        <Spin spinning={loading}>
                            {effectsForCurrentTab.length > 0 ? (
                                <Select
                                    placeholder="请选择或清除效果"
                                    allowClear
                                    showSearch
                                    filterOption={(input, option) => (option?.children?.toString() || '').toLowerCase().includes(input.toLowerCase())}
                                    // ✅ [核心修改 3]：将新的处理函数绑定到 Select 的 onChange 事件
                                    onChange={handleEffectChange}
                                    style={{ width: '98%' }}
                                >
                                    {effectsForCurrentTab.map((effect: any) => (
                                        <Option key={effect.name} value={effect.name}>
                                            {effect.display_name}
                                            {effect.is_vip ? ' (VIP)' : ''}
                                        </Option>
                                    ))}
                                </Select>
                            ) : (
                                <Alert message="暂无可用效果" type="info" showIcon />
                            )}
                        </Spin>
                    </Form.Item>
                </Form>
            </>
        );
    };

    if (!audioId) {
        return (
            <div
                style={{
                    padding: '20px',
                    color: '#FFFFFF',
                    backgroundColor: '#282828',
                    height: '100%',
                }}
            >
                未选择任何音频片段
            </div>
        );
    }

    return (
        <>
            <GlobalAntdDarkThemeStyle />
            <div
                className="config-panel-scroll"
                style={{
                    maxHeight: 540,
                    overflowX: 'hidden',
                    overflowY: 'auto',
                    backgroundColor: '#282828',
                    color: '#FFFFFF',
                    padding: '16px',
                    borderRadius: '8px',
                }}
            >
                <Title level={4} style={{ marginBottom: 16, color: '#FFFFFF' }}>
                    属性面板
                </Title>
                {renderContent()}
            </div>
        </>
    );
};

export default ConfigAudioEffectForm;
